package com.spzx.cart.service.impl;

import com.spzx.cart.api.domain.CartInfo;
import com.spzx.cart.service.CartInfoService;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.constant.ServiceNameConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domin.ProductSku;
import com.spzx.product.vo.SkuPriceVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartInfoServiceImpl implements CartInfoService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RemoteProductService remoteProductService;


    @Override
    public void addtocart(Long skuId, Integer num) {
        //先判断有没有这个商品
        Long userId = SecurityContextHolder.getUserId();
        String cartkey = getCartKey(userId);
        String productkey = skuId.toString();
        Boolean b = redisTemplate.opsForHash().hasKey(cartkey, productkey);
        if (b) {
            //商品存在更新数量
            CartInfo cartInfo = (CartInfo) redisTemplate.opsForHash().get(cartkey, productkey);
            Integer skuNum = cartInfo.getSkuNum();
            //每件商品数量最多99件
            cartInfo.setSkuNum(skuNum + num > 99 ? 99 : skuNum + num);
            cartInfo.setCreateTime(new Date());
            redisTemplate.opsForHash().put(cartkey, productkey, cartInfo);
        } else {
            //商品不存在就加入到购物车
            Long size = redisTemplate.opsForHash().size(cartkey);
            //最多加入五十件不同的商品
            if (size > 50) {
                throw new RuntimeException("最多加五十件商品");
            }
            //获取商品的信息,远程调用商品服务
            R<ProductSku> p = remoteProductService.getProductSku(skuId, SecurityConstants.INNER);
            if (p.getCode() != 200) {
                throw new ServiceException("远程调用服务失败,原因:" + p.getMsg());
            }
            ProductSku productSku = p.getData();
            //构建商品对象
            CartInfo cartInfo = new CartInfo();
            cartInfo.setUserId(userId);
            cartInfo.setSkuId(skuId);
            cartInfo.setCartPrice(productSku.getSalePrice());
            cartInfo.setSkuPrice(productSku.getSalePrice());
            cartInfo.setSkuNum(num > 99 ? 99 : num);
            cartInfo.setThumbImg(productSku.getThumbImg());
            cartInfo.setSkuName(productSku.getSkuName());
            cartInfo.setIsChecked(1);
            cartInfo.setCreateTime(new Date());
            //将对象写入redis
            redisTemplate.opsForHash().put(cartkey, productkey, cartInfo);
        }
    }

    @Override
    public List<CartInfo> cartlist() {
        //获取大key
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = this.getCartKey(userId);
        //获取数据
        List<CartInfo> cartInfoList = redisTemplate.opsForHash().values(cartKey);
        if (!ObjectUtils.isEmpty(cartInfoList)) {
            List<CartInfo> collect = cartInfoList.stream()
                    .sorted((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()))
                    .collect(Collectors.toList());
            return collect;
        }
        return new ArrayList<>();
    }

    @Override
    public void checkcart(Long skuId, Integer isChecked) {
        //先获取大key
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = this.getCartKey(userId);
        BoundHashOperations<String,String,CartInfo> boundHashOps = redisTemplate.boundHashOps(cartKey);
        CartInfo cartInfo = boundHashOps.get(skuId.toString());
        cartInfo.setIsChecked(isChecked);
        boundHashOps.put(skuId.toString(),cartInfo);
    }

    @Override
    public void callcheckcart(Integer isChecked) {
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = this.getCartKey(userId);
        BoundHashOperations<String,String,CartInfo> boundHashOperations = redisTemplate.boundHashOps(cartKey);
        //获取全部的商品
        List<CartInfo> cartInfoList = boundHashOperations.values();
        cartInfoList.forEach(cart -> {
            CartInfo cartInfo = boundHashOperations.get(cart.getSkuId().toString());
            cartInfo.setIsChecked(isChecked);
            boundHashOperations.put(cart.getSkuId().toString(),cartInfo);
        });
    }

    @Override
    public void deletecart(Long skuId) {
        //删除某个商品
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = this.getCartKey(userId);
        BoundHashOperations<String,String,CartInfo> boundHashOperations = redisTemplate.boundHashOps(cartKey);
        boundHashOperations.delete(skuId.toString());
    }

    @Override
    public void clearcart() {
        //清空购物车
        Long userId = SecurityContextHolder.getUserId();
        String cartKey = this.getCartKey(userId);
        redisTemplate.delete(cartKey);
    }

    @Override
    public List<CartInfo> getcartcheckedlist() {
        //查选中的商品信息
        String cartKey = this.getCartKey(SecurityContextHolder.getUserId());
        BoundHashOperations<String,String,CartInfo> boundHashOperations = redisTemplate.boundHashOps(cartKey);
        List<CartInfo> cartInfos = boundHashOperations.values();
        if (!ObjectUtils.isEmpty(cartInfos)){
            List<CartInfo> cartInfoList = cartInfos
                    .stream()
                    .filter(cartInfo -> cartInfo.getIsChecked() == 1)
                    .collect(Collectors.toList());
            return cartInfoList;
        }
        return null;
    }

    @Override
    public Boolean updateCartPrice() {
        String cartKey = this.getCartKey(SecurityContextHolder.getUserId());
        BoundHashOperations<String,String,CartInfo> boundHashOperations = redisTemplate.boundHashOps(cartKey);
        //得到所有的商品信息
        List<CartInfo> cartInfos = boundHashOperations.values();
        //遍历更新价格
        if (!ObjectUtils.isEmpty(cartInfos)){
            for (CartInfo cartInfo : cartInfos) {
                //调用商品远程服务获取最新价格
                R<SkuPriceVo> skuPrice = remoteProductService.getSkuPrice(cartInfo.getSkuId(), SecurityConstants.INNER);
                if (skuPrice.getCode()==R.FAIL){
                    throw new ServiceException("远程调用服务失败");
                }
                SkuPriceVo skuPriceVo = skuPrice.getData();
                cartInfo.setCartPrice(skuPriceVo.getSalePrice());
                boundHashOperations.put(cartInfo.getSkuId().toString(),cartInfo);
            }
        }
        return null;
    }

    @Override
    public Boolean deleteCartCheckedList() {
        String cartKey = this.getCartKey(SecurityContextHolder.getUserId());
        BoundHashOperations<String,String,CartInfo> boundHashOperations = redisTemplate.boundHashOps(cartKey);
        List<CartInfo> cartInfos = boundHashOperations.values();
        if(!ObjectUtils.isEmpty(cartInfos)){
             cartInfos.stream()
                    .filter(cartInfo -> cartInfo.getIsChecked() == 1)
                    .forEach(cartInfo -> boundHashOperations.delete(cartInfo.getSkuId().toString()));
        }
        return null;
    }

    private String getCartKey(Long userId) {
        //定义key user:userId:cart
        return "user:cart:" + userId;
    }
}
